package com.ruoyi.yuyuan.Utils;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.List;

@Component
@Slf4j
public class MailUtil {
    @Value("${spring.mail.username}")
    private String address;

    @Autowired
    private JavaMailSender mailSender;

    /**
     * 简单邮件
     * @param subject 标题
     * @param context 内容
     */
    public void sendSimpleMail(String subject,String context){
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(address);
        message.setTo(address);
        message.setSubject(subject);
        message.setText(context);
        mailSender.send(message);
    }

    /**
     * 带附件邮件
     * @param subject 标题
     * @param context 内容
     * @param files 附件
     */
    //带附件的邮件
    public void sendAttachFileMail(String subject, String context, List<File> files){
        try{
            javax.mail.internet.MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message,true);
            helper.setFrom(address);
            helper.setTo(address);
            helper.setSubject(subject);
            helper.setText(context);
            for (File file : files) {
                helper.addAttachment(file.getName(),file);//传入文件
            }
            mailSender.send(message);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
